package com.iexbuy.ihg.ui.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.iexbuy.ihg.R;
import com.iexbuy.ihg.adapter.ShopCenterAdapter;
import com.iexbuy.ihg.adapter.ShopsAdapter;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.common.ExtraKeyConstant;
import com.iexbuy.ihg.entity.BusinessType;
import com.iexbuy.ihg.entity.CityObject;
import com.iexbuy.ihg.entity.DistrictObject;
import com.iexbuy.ihg.entity.Shop;
import com.iexbuy.ihg.entity.ShopCenter;
import com.iexbuy.ihg.entity.ShopCenterListResponse;
import com.iexbuy.ihg.entity.ShopCenterResponse;
import com.iexbuy.ihg.entity.ShopResponse;
import com.iexbuy.ihg.entity.ZoomObject;
import com.iexbuy.ihg.entity.ZoomObjectResponce;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.StringUtil;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShopCenterSearchResultFragment extends BaseFragment {

	private final static String ALL_IND = "-100";
	
	private static ShopCenterSearchResultFragment homeFragmentInstent;

	@ViewInject(R.id.msgListLayout)
	private PullToRefreshLayout msgListLayout;
	@ViewInject(R.id.listView)
	private ListView listView;
	@ViewInject(R.id.emptyText)
	private TextView emptyText;
	@ViewInject(R.id.distictListView)
	private ListView distictListView;
	@ViewInject(R.id.busEreaListView)
	private ListView busEreaListView;
	@ViewInject(R.id.categoryListView)
	private ListView categoryListView;
	@ViewInject(R.id.currentCity)
	private EditText currentCity;
	@ViewInject(R.id.cityLayout)
	private LinearLayout cityLayout;
	@ViewInject(R.id.categoryLayout)
	private LinearLayout categoryLayout;
	@ViewInject(R.id.distictLayout)
	private LinearLayout distictLayout;
	@ViewInject(R.id.locationBtn)
	private Button locationBtn;
	@ViewInject(R.id.categoryBtn)
	private Button categoryBtn;


	private static List<ShopCenter> shopCenterListObjects = new ArrayList<ShopCenter>();

	private static List<BusinessType> businessTypes = new ArrayList<BusinessType>();
	private int pageNo = 0;
	private boolean hasNextPage;

	private ShopCenterAdapter shopCenterAdapter;



	private String zoomCode;
	private String distanceCode;
	private static String distanceName;
	private static String cityCode;
	private String categoryId;

	private static List<DistrictObject> districtObjects = new ArrayList<DistrictObject>();
	private List<ZoomObject> zoomObjects = new ArrayList<ZoomObject>();
	//全部分类
	private List<ZoomObject> categoryObjects = new ArrayList<ZoomObject>();
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		homeFragmentInstent = this;
	}

	@Override
	protected View _onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_shopcenter_search_result, container, false);
		ViewUtils.inject(this, rootView);
		initView(rootView);
		return rootView;
	}

	private void initView(View rootView) {
		mBaseActivity.setTitle("购物中心专场");
		msgListLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
				refreshDate();
			}

			@Override
			public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {

				if (hasNextPage) {
					loadMore();
				} else {
					msgListLayout.refreshFinish(PullToRefreshLayout.DONE);
				}
			}
		});

		if(shopCenterListObjects.size()==0){
			refreshDate();
		}else {
			initShopCenterListView();
		}
		districtObjects.clear();
		districtObjects.addAll(HomeFragment.getDistrictObjects());
		categoryBtn.setText("全部类别");
		initDistanceView();
		initCategory();

	}
	//测试数据
	private void initListView() {

	}

	//刷新整个页面数据
	private void refreshDate() {
		//获取服务器的所搜索的信息
		getSearchShopCenters();
	}

	/**
	 * 查询购物中心
	 */
	public void getSearchShopCenters() {

			HashMap<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("latitude", CommUtil.getLatitude());
			paramMap.put("longitude", CommUtil.getLongitude());
			paramMap.put("pageNo", String.valueOf(pageNo));
			paramMap.put("pageSize", String.valueOf(ExtraKeyConstant.COMMON_PAGE_SIZE));

			if (StringUtil.isNotEmpty(cityCode)) {
				paramMap.put("city", cityCode);
			}
			if (StringUtil.isNotEmpty(categoryId)) {
				paramMap.put("categoryId", categoryId);
			}
			if (StringUtil.isNotEmpty(distanceCode)) {
				paramMap.put("district", distanceCode);

			}
			if (StringUtil.isNotEmpty(zoomCode)) {
				paramMap.put("area", zoomCode);

			}
			ServiceHelper.send(mBaseActivity, ServiceHelper.GET_SHOP_CENTERS, paramMap,
					new RequestCallBack<String>() {
						@Override
						public void onStart() {
						}

						@Override
						public void onCancelled() {
						}

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							msgListLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
							ShopCenterListResponse rsp = JsonUtils.parseJsonStrToObject(responseInfo.result, ShopCenterListResponse.class);
							hasNextPage = rsp.getBody().isHasNext();
							if (pageNo == 0) {
								shopCenterListObjects.clear();
							}
							if (rsp.getBody() != null) {
								shopCenterListObjects.addAll(rsp.getBody().getData());

								if (shopCenterListObjects.size() > 0) {
									initShopCenterListView();
								}
							}
						}

						@Override
						public void onFailure(HttpException error, String msg) {
							msgListLayout.refreshFinish(PullToRefreshLayout.FAIL);
						}
					});


	}

	private void loadMore() {
		pageNo ++;
		getSearchShopCenters();
	}

	private void initShopCenterListView() {
		if (shopCenterAdapter == null) {
			shopCenterAdapter = new ShopCenterAdapter(mBaseActivity, shopCenterListObjects);
			listView.setAdapter(shopCenterAdapter);
		}
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
				ShopCenterDetailFragment.setShopCenter(shopCenterListObjects.get(i));
				CommUtil.openSingleFragmentActivity(mBaseActivity, ShopCenterDetailFragment.class);
			}
		});
		shopCenterAdapter.notifyDataSetChanged();
	}

	/**
	 * 显示区域搜索
	 */
	private void initDistanceView () {
		districtObjects.add(new DistrictObject("附近", ALL_IND));
		Collections.sort(districtObjects, new Comparator<DistrictObject>() {
			@Override
			public int compare(DistrictObject districtObject, DistrictObject t1) {
				return districtObject.getCode().compareTo(t1.getCode());
			}
		});
		distictListView.setAdapter(new BaseAdapter() {
			@Override
			public int getCount() {
				return districtObjects.size();
			}

			@Override
			public Object getItem(int i) {
				return districtObjects.get(i);
			}

			@Override
			public long getItemId(int i) {
				return 0;
			}

			@Override
			public View getView(int i, View view, ViewGroup viewGroup) {
				if (view == null) {
					view = LayoutInflater.from(mBaseActivity).inflate(R.layout.list_item_single_text, null);
				}
				((TextView) view.findViewById(R.id.itemName)).setText(districtObjects.get(i).getName());
				return view;
			}
		});
		distictListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
				if (ALL_IND.equalsIgnoreCase(districtObjects.get(i).getCode())) {
					distanceCode = "";
					locationBtn.setText("附近");
					getSearchShopCenters();
					hideCityCategoryLayout();
				} else {
					distanceCode = districtObjects.get(i).getCode();
					distanceName = districtObjects.get(i).getName();
					getBusEreaListData();
				}
			}
		});
	}

	/**
	 * 查询所以购物中心分类  区域查询
	 */
	private void getBusEreaListData() {
		HashMap<String, String> paramMap = new HashMap<String, String>();

		paramMap.put("cityCode", distanceCode);
		ServiceHelper.send(mBaseActivity, ServiceHelper.GET_DISTRICT_BY_CITY_CODE, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
					}

					@Override
					public void onCancelled() {
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						ZoomObjectResponce rsp = JsonUtils.parseJsonStrToObject(responseInfo.result, ZoomObjectResponce.class);
						zoomObjects.clear();
						if (rsp.getBody() != null) {
							zoomObjects.addAll(rsp.getBody());
						}
						initZoomListView();
					}

					@Override
					public void onFailure(HttpException error, String msg) {
					}
				});
	}

	private void initZoomListView() {
		zoomObjects.add(new ZoomObject("全部类别", ALL_IND));
		Collections.sort(zoomObjects, new Comparator<ZoomObject>() {
			@Override
			public int compare(ZoomObject zoomObject, ZoomObject t1) {
				return zoomObject.getCode().compareTo(t1.getCode());
			}
		});
		busEreaListView.setAdapter(new BaseAdapter() {
			@Override
			public int getCount() {
				return zoomObjects.size();
			}

			@Override
			public Object getItem(int i) {
				return zoomObjects.get(i);
			}

			@Override
			public long getItemId(int i) {
				return 0;
			}

			@Override
			public View getView(int i, View view, ViewGroup viewGroup) {
				if (view == null) {
					view = LayoutInflater.from(mBaseActivity).inflate(R.layout.list_item_single_text, null);
				}
				((TextView) view.findViewById(R.id.itemName)).setText(zoomObjects.get(i).getName());
				return view;
			}
		});
		busEreaListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
				if (ALL_IND.equalsIgnoreCase(zoomObjects.get(i).getCode())) {
					zoomCode = "";
					locationBtn.setText(distanceName);
				} else {
					zoomCode = zoomObjects.get(i).getCode();
					locationBtn.setText(zoomObjects.get(i).getName());

				}
				hideCityCategoryLayout();
				getSearchShopCenters();
			}
		});
	}

	/**
	 * 显示购物中心类别
	 */
	private void initCategory() {

		//获取分类
		HashMap<String, String> paramMap = new HashMap<String, String>();
		ServiceHelper.send(mBaseActivity, ServiceHelper.GET_SHOP_CENTER_CATEGORYS, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
					}

					@Override
					public void onCancelled() {
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						Map<String,String> map=JsonUtils.getJsonByKey(responseInfo.result,"body");

						for(int i=0;i<map.size();i++){
							String key = map.get(""+(i+1));
							ZoomObject zoomObject = new ZoomObject(key,(i+1)+"");
							categoryObjects.add(zoomObject);
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
					}
				});
		categoryObjects.add(new ZoomObject("全部类别", ALL_IND));
		Collections.sort(categoryObjects, new Comparator<ZoomObject>() {
			@Override
			public int compare(ZoomObject zoomObject, ZoomObject t1) {
				return zoomObject.getCode().compareTo(t1.getCode());
			}
		});

		categoryListView.setAdapter(new BaseAdapter() {
			@Override
			public int getCount() {
				return categoryObjects.size();
			}

			@Override
			public Object getItem(int i) {
				return categoryObjects.get(i);
			}

			@Override
			public long getItemId(int i) {
				return 0;
			}

			@Override
			public View getView(int i, View view, ViewGroup viewGroup) {
				if (view == null) {
					view = LayoutInflater.from(mBaseActivity).inflate(R.layout.list_item_single_text, null);
				}
				((TextView) view.findViewById(R.id.itemName)).setText(categoryObjects.get(i).getName());
				return view;
			}
		});
		categoryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
				if (ALL_IND.equalsIgnoreCase(categoryObjects.get(i).getCode())) {
					categoryId = "";
					categoryBtn.setText("全部类别");
				} else {
					categoryId = categoryObjects.get(i).getCode();
					categoryBtn.setText(categoryObjects.get(i).getName());
				}
				hideCityCategoryLayout();
				getSearchShopCenters();
			}
		});
	}

	@OnClick(R.id.locationBtn)
	public void locationBtnClick(View view) {
		if(cityLayout.isShown()){
			cityLayout.setVisibility(View.GONE);
		}else{
			cityLayout.setVisibility(View.VISIBLE);
		}

		categoryLayout.setVisibility(View.GONE);
	}

	@OnClick(R.id.categoryBtn)
	public void categoryBtnClick(View view) {
		if(categoryLayout.isShown()){
			categoryLayout.setVisibility(View.GONE);
		}else{
			categoryLayout.setVisibility(View.VISIBLE);
		}
		cityLayout.setVisibility(View.GONE);

	}
	@OnClick(R.id.cityLayoutMask)
	public void cityLayoutMaskClick(View view){
		hideCityCategoryLayout();
	}
	@OnClick(R.id.categoryLayoutMask)
	public void categoryLayoutMaskClick(View view){
		hideCityCategoryLayout();
	}

	private void hideCityCategoryLayout() {
		cityLayout.setVisibility(View.GONE);
		categoryLayout.setVisibility(View.GONE);
	}

	public static void setCityCode(String cityCode) {
		ShopCenterSearchResultFragment.cityCode = cityCode;
	}
	public static void setShopCenters(List<ShopCenter> shopCenterListObjects) {
		ShopCenterSearchResultFragment.shopCenterListObjects = shopCenterListObjects;
	}


	/**
	 * @return the homeFragmentInstent
	 */
	public static ShopCenterSearchResultFragment getHomeFragmentInstent() {
		return homeFragmentInstent;
	}

}
